package com.blockmeta.bbs.businesslibrary.provider;

import android.app.Application;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.embedding.android.FlutterView;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.StandardMessageCodec;

import com.blankj.utilcode.util.LogUtils;

import com.blockmeta.bbs.businesslibrary.net.retrofit.BaseOKHttpClient;
import com.blockmeta.bbs.businesslibrary.widget.ForegroundCallbacks;
import com.blockmeta.bbs.businesslibrary.widget.emoji.EmojiManager;
import com.hellobike.flutter.thrio.module.ThrioModule;
import com.liulishuo.filedownloader.FileDownloader;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.BuildConfig;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.vanniktech.emoji.ios.IosEmojiProvider;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @author AirThor
 * @date 2019/6/13.
 * 初始化第三方sdk
 */
public class InitSdkProvider extends ContentProvider {
    private Context mContext;
    private static final String QKL123 = "com.qkl123.android";
    private static final String CHAINNODE = "com.blockmeta.chainnode";

    @Override
    public boolean onCreate() {
        mContext = getContext();
        //友盟初始化各个平台的信息
        initPlatformConfig();
        initOkHttp();
        initTBS();
        //初始化emoji
        EmojiManager.install(new IosEmojiProvider());
        com.vanniktech.emoji.EmojiManager.install(new IosEmojiProvider());
        ForegroundCallbacks.init((Application) mContext);
        FileDownloader.setupOnApplicationOnCreate((Application) mContext.getApplicationContext());
        initBugly(mContext);

        return true;
    }

    private void initBugly(Context context) {
        //腾讯错误统计
        // 建议在测试阶段建议设置成true，发布时设置为false。
        String packageName = mContext.getPackageName();
        String appId;
        if (QKL123.equals(packageName)){
            appId = "6dd3fc48ce";
        }else if (CHAINNODE.equals(packageName)){
            appId = "52d19b43c3";
        }else {
            appId = "2128643202";
        }
        CrashReport.initCrashReport(context, appId, false);
    }

    /**
     * 友盟初始化各个平台的信息
     */
    private void initPlatformConfig() {
        String packageName = mContext.getPackageName();
        String uMengKey;
        Config.DEBUG=true;

        PlatformConfig.setSinaWeibo("4173845985", "a3c6a069f540338b76d7118ec0767538App", "http://sns.whalecloud.com");
        PlatformConfig.setQQZone("101391594", "13af0d67a092a1842efa0de0202bc907");
        PlatformConfig.setWeixin("wxed9601d0212364cb", "553dd90c298125da515f9ba16c6d04a2");

        uMengKey = "5fd8cfaf498d9e0d4d8fc733";

        initUmeng(uMengKey);
    }

    /**
     * 初始化腾讯X5浏览器
     */
    private void initTBS() {
        QbSdk.initX5Environment(mContext, new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {
                //x5内核初始化完成回调接口，此接口回调并表示已经加载起来了x5，有可能特殊情况下x5内核加载失败，切换到系统内核。
            }

            @Override
            public void onViewInitFinished(boolean b) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                LogUtils.d("sss", "加载内核是否成功:" + b);
            }
        });
    }

    private void initOkHttp() {
        OkHttpUtils.initClient(BaseOKHttpClient.getIns().buildClient());
    }
    /**
     * 初始化友盟
     */
    private void initUmeng(String key) {
        Config.DEBUG = true;
        UMConfigure.setLogEnabled(true);
        String channel = readContent("channel");
        UMConfigure.init(mContext, key, channel, UMConfigure.DEVICE_TYPE_PHONE, "");
        //um分享登陆初始化
        UMShareAPI.get(mContext);
        //禁止um默认的页面统计模式
        MobclickAgent.openActivityDurationTrack(false);

        if (BuildConfig.DEBUG) {
            //开发时关闭错误统计
            MobclickAgent.setCatchUncaughtExceptions(false);
        }
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        return null;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }

    /**
     * 读取asset文件内容
     *
     * @param path
     * @return
     */
    public  String readContent(String path) {
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        try
        {
            reader = new BufferedReader(
                    new InputStreamReader(mContext.getAssets().open(path), "UTF-8"));
            // do reading, usually loop until end of file reading
            char[] chars = new char[1024];
            int read = 0;
            while ((read = reader.read(chars)) >= 0)
            {
                buffer.append(chars, 0, read);
            }
        }
        catch (IOException e)
        {
        }
        finally
        {
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (IOException e)
                {
                    //log the exception
                }
            }
        }
        return buffer.toString();
    }
}
